import pygame
import calc
from typing import Tuple, List

def drawline(screen: pygame.Surface, line: calc.Line, width:int, color: Tuple[int, int, int]):
    pygame.draw.line(screen, color, (line.start_node.x(), line.start_node.y()), (line.end_node.x(), line.end_node.y()), width)

# 画交通信号灯 TODO：在Node类中添加交通信号灯的坐标
def drawtrafficlight(screen: pygame.Surface, signal: calc.TrafficLight, text_position: Tuple[int, int]):
    font = pygame.font.Font(None, 36)
    color = signal.get_color()
    text_surface = font.render(str(signal.get_shownumber()), True, color)
    # text_position = (signal.get_x(), signal.get_y())
    screen.blit(text_surface, text_position)

def drawcarqueue(screen: pygame.Surface, car_queue: List[calc.Car]):
    if car_queue is None:
        return
    for car in car_queue:
        drawcar(screen, car)

def drawcarqueues(screen: pygame.Surface, car_queues: List[List[calc.Car]]):
    for car_quque in car_queues:
        drawcarqueue(screen, car_quque)

def drawnode(screen: pygame.Surface, node: calc.Node):
    corex = node.rx()
    corey = node.ry()
    trfiNSD: calc.TrafficLight = node.get_trafficlight(calc.NSD)
    trfiEWD: calc.TrafficLight = node.get_trafficlight(calc.WED)
    drawtrafficlight(screen, trfiNSD, (corex, corey+trfiNSD.get_biasy()))
    drawtrafficlight(screen, trfiNSD, (corex, corey-trfiNSD.get_biasy()))
    drawtrafficlight(screen, trfiEWD, (corex+trfiEWD.get_biasx(), corey))    
    drawtrafficlight(screen, trfiEWD, (corex-trfiEWD.get_biasx(), corey))
    drawcarqueues(screen, node.straight_car_queues)
    drawcarqueues(screen, node.right_car_queues)
    drawcarqueues(screen, node.back_car_queues)

# 画车
def drawcar(screen: pygame.Surface, car: calc.Car):
    pygame.draw.circle(screen, car.color, (car.get_x(), car.get_y()), 3)

# 画路
def drawroad(screen: pygame.Surface, road: calc.Road, width:int, color: Tuple[int, int, int]):
    # 先画道路
    lines = road.getLines()
    for line in lines:
        if line is None:
            continue
        drawline(screen, line, width, color)
    # 再画路上的车
    for car_queue in road.car_queues:
        if car_queue is None:
            continue
        for car in car_queue:
            drawcar(screen, car)

# 画地图
def drawmap(screen: pygame.Surface, map: calc.Map, width:int, color: Tuple[int, int, int]):
    roads = map.getRoads()
    for road in roads:
        drawroad(screen, road, width, color)
    for node in map.trafficLightNodes:
        drawnode(screen, node)
